/**
 * 
 */
package com.fnic.pearl.scheduler.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * AES 加解密算法的常用工具
 * 
 * @author HuHaiyang
 * @date 2013年9月2日
 */
public class AesCipherUtil
{
    public static final String DEFAULT_TRANS = "AES/CBC/PKCS5Padding";
    public static final String DEFAULT_PROVIDER = "SunJCE";
    
    /**
     * 该方法用于协议内容的加密
     * 采用 aes(Rijndael-128) 算法
     * 
     * @return 加密后的内容
     * @throws Exception e 
     */
    public static byte[] encrypt(String plainText, String encryptionKey) throws Exception
    {
        Cipher cipher = Cipher.getInstance(DEFAULT_TRANS, DEFAULT_PROVIDER);
        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(plainText.getBytes("UTF-8"));
    }
    
    /**
     * 该方法用于协议内容的解密
     * 
     * @return 返回解密后的内容
     * @throws Exception e
     */
    public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception
    {
        Cipher cipher = Cipher.getInstance(DEFAULT_TRANS, DEFAULT_PROVIDER);
        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
        cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return new String(cipher.doFinal(cipherText),"UTF-8");
    }
}
